<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\UserCouponRecord;
use App\Services\Admin\Store;
use App\Services\Admin\User;
use Illuminate\Http\Request;
use App\Services\Admin\Coupon;
use App\Http\Requests\Admin\GouponController\doRule;

class GouponController extends Controller
{
    public function index()
    {

        $coupon_result = Coupon::lists()->paginate(15);

        foreach ($coupon_result as $v){
            $v->received_count = Coupon::user_coupon_record($v->id)->count();
        }

        $result = [
            'result'=>$coupon_result,
            'select_store'=>Store::where_lists(),
            'sear_value'=>\request()->get('sear_value'),
            'store_id'=>\request()->get('store_id'),
            'is_opend'=>\request()->get('is_opend'),
            'start_time'=>\request()->get('start_time'),
            'end_time'=>\request()->get('end_time'),
        ];

        return view('admin.coupon.index', $result);

    }

    public function recipients($id)
    {
        //查询领取记录
        $user_ids = Coupon::user_coupon_record($id)->pluck('user_id')->toArray();

        $result = [
            'result'=>User::lists()->whereIn('id', $user_ids)->paginate(15),
            'sear_value'=>request()->sear_value??'',
        ];

        return view('admin.coupon.user',$result);
    }

    public function add()
    {
        $result = [
            'select_store'=>Store::where_lists(),
            'result'=>'',
            'id'=>'',
        ];

        return view('admin.coupon.edit',$result);
    }

    public function edit(Request $request, $id)
    {
        $result = [
            'id'=>$id,
            'result'=> Coupon::info($id),
            'select_store'=>Store::where_lists(),
        ];

        return view( 'admin.coupon.edit', $result);
    }

    public function do(doRule $request)
    {
        if ($request->ajax()) {

            $input = $request->all();

            if (empty($input['id'])) {
                unset($input['id']);
                Coupon::add($input);
            } else {
                Coupon::edit($input['id'],$input);
            }

            return self::success([]);
        }
    }

    public function del($id)
    {

        Coupon::del($id);

        return self::success([]);

    }
}
